//
//  SelectContactController.swift
//  MoyoungDevice
//
//  Created by 易先生 on 2022/9/3.
//

import UIKit
import RxCocoa
import RxSwift
import CRPEarPhone
import EarbudsDatabase

class SelectContactController: ViewController {

	private lazy var viewModel = SelectContactViewModel()
	public var editContact: ContactModel?
	public var oldSelectCount = 0
	public var currentSelectContact: [ContactModel] = []

	public let selectContactRelay = PublishRelay<[ContactModel]>()

	override func viewDidLoad() {
		super.viewDidLoad()

        self.navigation.item.title = R.string.localizable.setting_contact_select()
//		self.navigation.item.leftBarButtonItem = leftBarButtonItem
		self.navigation.item.rightBarButtonItem = rightBarButtonItem
		viewModel.editContact = editContact
		viewModel.currentSelectContact = currentSelectContact
		viewModel.layerUI()
	}

	override func makeUI() {
		super.makeUI()
        
        view.backgroundColor = R.color.common_2_bg_page()
		view.addSubview(searchBar)
		view.addSubview(tableView)
		searchBar.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(kNavHeight)
			make.leading.trailing.equalToSuperview()
			make.height.equalTo(56)
		}

		tableView.snp.makeConstraints { make in
            make.top.equalTo(searchBar.snp.bottom)
			make.leading.trailing.bottom.equalToSuperview()
		}
	}

	override func bindViewModel() {
		super.bindViewModel()

		leftBarButtonItem.rx.tap.subscribe { [weak self] _ in
			guard let self = self else { return }
			self.navigationController?.popViewController(animated: true)
		}.disposed(by: rx.disposeBag)

		rightBarButtonItem.rx.tap.subscribe { [weak self] _ in
			guard let self = self else { return }

			self.selectContactRelay.accept(self.viewModel.currentSelectContact)
			self.navigationController?.popViewController(animated: true)
		}.disposed(by: rx.disposeBag)

		viewModel.reloadTableViewRelay.subscribe { [weak self] _ in
			guard let self = self else { return }
			DispatchQueue.main.async {
				self.changeRightBarTitle()
				self.tableView.reloadData()
			}
		}.disposed(by: rx.disposeBag)
	}

	private func changeRightBarTitle() {
		if self.viewModel.currentSelectContact.count > 0 && self.editContact == nil {
            self.rightBarButtonItem.title =   "\(R.string.localizable.common_save())(\(self.viewModel.currentSelectContact.count - self.oldSelectCount))"
		} else {
			self.rightBarButtonItem.title = R.string.localizable.common_save()
		}
	}

	private lazy var leftBarButtonItem: UIBarButtonItem = {
		let leftBarButtonItem = UIBarButtonItem()
        leftBarButtonItem.title = R.string.localizable.common_cancel()
		return leftBarButtonItem
	}()

	private lazy var rightBarButtonItem: UIBarButtonItem = {
		let rightBarButtonItem = UIBarButtonItem()
		return rightBarButtonItem
	}()

	private lazy var searchBar: UISearchBar = {
		let searchBar = UISearchBar()
        searchBar.setImage(R.image.ic_common_search(), for: .search, state: .normal)
		searchBar.showsCancelButton = false
		searchBar.delegate = self
		searchBar.barStyle = .default
		searchBar.searchBarStyle = .minimal
        searchBar.placeholder = R.string.localizable.setting_contact_search()
		if let searchField = searchBar.value(forKey: "searchField") as? UITextField {
            searchField.textColor = R.color.common_23_text_second()
		}
		searchBar.isTranslucent = false
		searchBar.showsScopeBar = true
		return searchBar
	}()

	private lazy var tableView: TableView = {
		let tableView = TableView(frame: .zero, style: .grouped)
        tableView.backgroundColor = R.color.common_2_bg_page()
		tableView.estimatedRowHeight = 60
		tableView.estimatedSectionFooterHeight = 0
		tableView.estimatedSectionHeaderHeight = 30
		tableView.sectionFooterHeight = 0
		tableView.separatorColor = R.color.common_6_line()
		tableView.delegate = self
		tableView.dataSource = self
        tableView.sectionIndexColor = R.color.common_16_bg()
        tableView.sectionIndexBackgroundColor = .clear
		tableView.register(SelectFriendCell.self, forCellReuseIdentifier: SelectFriendCell.reuseIdentifier)
		tableView.register(SelectPhoneCell.self, forCellReuseIdentifier: SelectPhoneCell.reuseIdentifier)
		tableView.tableFooterView = UIView()
		return tableView
	}()

}

extension SelectContactController: UISearchBarDelegate {

	func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
		searchBar.resignFirstResponder()
		self.navigationController?.popViewController(animated: true)
	}

	func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
		if let str = searchBar.text {
			viewModel.filterBySubstring(str: str)
		}
	}

	func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
		viewModel.filterBySubstring(str: searchText)
	}
}

extension SelectContactController: UITableViewDataSource {

	func numberOfSections(in tableView: UITableView) -> Int {
		return viewModel.numberOfSections()
	}

	func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return viewModel.numberOfRowsInSection(section: section)
	}

	func sectionIndexTitles(for tableView: UITableView) -> [String]? {
		return viewModel.sectionStrings
	}

	func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
		let sectionView = View(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 30))
        sectionView.backgroundColor = R.color.common_10_bg_page()
		let titleLabel = Label(frame: CGRect(x: 20, y: 0, width: view.bounds.size.width - 40, height: 30))
		titleLabel.text = viewModel.titleForHeaderInSection(section: section)
		titleLabel.textColor = R.color.common_23_text_second()
		titleLabel.font = Fonts.systemFont(ofSize: 14)
		sectionView.addSubview(titleLabel)
		return sectionView
	}

	func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

		let contact = viewModel.getCurrentContact(indexPath: indexPath)

		guard let currentContact = contact else {
			return UITableViewCell()
		}

		if currentContact.phoneNumbers.count > 1 {
			if currentContact.phoneNumbers.firstIndex(of: currentContact.selectPhoneNumber) != nil {
				let cell = tableView.dequeueReusableCell(withIdentifier: SelectPhoneCell.reuseIdentifier) as! SelectPhoneCell
				if currentContact.selectPhoneNumber == currentContact.phoneNumbers.last {
					cell.configImage(contact: currentContact, image: viewModel.lastImage)
					cell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
				} else {
					cell.configImage(contact: currentContact, image: viewModel.midImage)
					cell.separatorInset = UIEdgeInsets(top: cell.height - 1, left: 70, bottom: 0, right: 20)
				}
				cell.configSelect(currentSelectContact: viewModel.currentSelectContact, contact: currentContact)
				return cell
			} else {
				let cell = tableView.dequeueReusableCell(withIdentifier: SelectFriendCell.reuseIdentifier) as! SelectFriendCell
				cell.configModel(contact: currentContact)
				cell.separatorInset = UIEdgeInsets(top: cell.height - 1, left: 70, bottom: 0, right: 20)
				return cell
			}

		} else {
			let cell = tableView.dequeueReusableCell(withIdentifier: SelectFriendCell.reuseIdentifier) as! SelectFriendCell
			cell.configSelect(currentSelectContact: viewModel.currentSelectContact, contact: currentContact)
            cell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
			return cell
		}
	}
}

extension SelectContactController: UITableViewDelegate {

	func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
		return viewModel.heightForHeaderInSection(section: section)
	}

	func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

		viewModel.didSelectRowAt(indexPath: indexPath)
	}
}
